#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <fcntl.h>

#define PORT 8080
#define BUFFER_SIZE 1024
#define ROOT_DIR "./www"  // 静态文件根目录

// 发送 HTTP 响应头
void send_http_header(int client_socket, int status_code, const char *content_type, long content_length) {
    const char *status_line;
    if (status_code == 200) {
        status_line = "HTTP/1.1 200 OK\r\n";
    } else if (status_code == 404) {
        status_line = "HTTP/1.1 404 Not Found\r\n";
    } else if (status_code == 500) {
        status_line = "HTTP/1.1 500 Internal Server Error\r\n";
    } else {
        status_line = "HTTP/1.1 400 Bad Request\r\n";
    }

    char response[BUFFER_SIZE];
    sprintf(response, "%s"
                      "Content-Type: %s\r\n"
                      "Content-Length: %ld\r\n"
                      "Connection: close\r\n"
                      "\r\n",
            status_line, content_type, content_length);
    send(client_socket, response, strlen(response), 0);
}

// 获取文件的 MIME 类型
const char *get_mime_type(const char *filename) {
    const char *ext = strrchr(filename, '.');
    if (!ext) return "text/plain";
    
    if (strcmp(ext, ".html") == 0 || strcmp(ext, ".htm") == 0) return "text/html";
    if (strcmp(ext, ".css") == 0) return "text/css";
    if (strcmp(ext, ".js") == 0) return "application/javascript";
    if (strcmp(ext, ".jpg") == 0 || strcmp(ext, ".jpeg") == 0) return "image/jpeg";
    if (strcmp(ext, ".png") == 0) return "image/png";
    if (strcmp(ext, ".gif") == 0) return "image/gif";
    if (strcmp(ext, ".pdf") == 0) return "application/pdf";
    
    return "text/plain";
}

// 处理客户端请求
void handle_client(int client_socket) {
    char request[BUFFER_SIZE] = {0};
    recv(client_socket, request, BUFFER_SIZE - 1, 0);
    
    // 解析请求行（例如：GET /index.html HTTP/1.1）
    char method[32], path[256], version[32];
    sscanf(request, "%s %s %s", method, path, version);
    
    // 只处理 GET 请求
    if (strcmp(method, "GET") != 0) {
        send_http_header(client_socket, 400, "text/html", 0);
        close(client_socket);
        return;
    }
    
    // 构建文件路径
    char file_path[256];
    if (strcmp(path, "/") == 0) {
        strcpy(file_path, ROOT_DIR);
        strcat(file_path, "/index.html");
    } else {
        strcpy(file_path, ROOT_DIR);
        strcat(file_path, path);
    }
    
    // 检查文件是否存在
    struct stat file_stat;
    if (stat(file_path, &file_stat) == -1) {
        // 文件不存在，返回 404
        const char *not_found_content = "<h1>404 Not Found</h1>";
        send_http_header(client_socket, 404, "text/html", strlen(not_found_content));
        send(client_socket, not_found_content, strlen(not_found_content), 0);
        close(client_socket);
        return;
    }
    
    // 检查是否为目录
    if (S_ISDIR(file_stat.st_mode)) {
        // 是目录，尝试查找 index.html
        char index_path[256];
        strcpy(index_path, file_path);
        strcat(index_path, "/index.html");
        if (stat(index_path, &file_stat) == 0) {
            strcpy(file_path, index_path);
        } else {
            const char *forbidden_content = "<h1>403 Forbidden</h1>";
            send_http_header(client_socket, 403, "text/html", strlen(forbidden_content));
            send(client_socket, forbidden_content, strlen(forbidden_content), 0);
            close(client_socket);
            return;
        }
    }
    
    // 打开文件
    int file_fd = open(file_path, O_RDONLY);
    if (file_fd == -1) {
        // 无法打开文件，返回 500
        const char *error_content = "<h1>500 Internal Server Error</h1>";
        send_http_header(client_socket, 500, "text/html", strlen(error_content));
        send(client_socket, error_content, strlen(error_content), 0);
        close(client_socket);
        return;
    }
    
    // 获取文件类型
    const char *mime_type = get_mime_type(file_path);
    
    // 发送响应头
    send_http_header(client_socket, 200, mime_type, file_stat.st_size);
    
    // 发送文件内容
    char buffer[BUFFER_SIZE];
    ssize_t bytes_read;
    while ((bytes_read = read(file_fd, buffer, BUFFER_SIZE)) > 0) {
        send(client_socket, buffer, bytes_read, 0);
    }
    
    // 关闭文件和客户端连接
    close(file_fd);
    close(client_socket);
}

int main() {
    int server_fd, client_socket;
    struct sockaddr_in address;
    int opt = 1;
    int addrlen = sizeof(address);
    
    // 创建套接字
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
        perror("socket failed");
        exit(EXIT_FAILURE);
    }
    
    // 设置套接字选项
    if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt))) {
        perror("setsockopt");
        exit(EXIT_FAILURE);
    }
    
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(PORT);
    
    // 绑定套接字
    if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
        perror("bind failed");
        exit(EXIT_FAILURE);
    }
    
    // 监听连接
    if (listen(server_fd, 3) < 0) {
        perror("listen");
        exit(EXIT_FAILURE);
    }
    
    printf("HTTP Server listening on port %d...\n", PORT);
    printf("Serving files from directory: %s\n", ROOT_DIR);
    
    // 主循环接受客户端连接
    while (1) {
        if ((client_socket = accept(server_fd, (struct sockaddr *)&address, 
                                   (socklen_t*)&addrlen)) < 0) {
            perror("accept");
            exit(EXIT_FAILURE);
        }
        
        // 处理客户端请求（单线程版本）
        handle_client(client_socket);
    }
    
    return 0;
}    